package com.cskaoyan.user.service.impl;

import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.mall.commons.exception.ValidateException;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.entitys.UserVerify;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dal.persistence.UserVerifyMapper;
import com.cskaoyan.user.dto.UserRegisterRequest;
import com.cskaoyan.user.dto.UserRegisterResponse;
import com.cskaoyan.user.dto.UserVerifyRequest;
import com.cskaoyan.user.dto.UserVerifyResponse;
import com.cskaoyan.user.service.IRegisterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author Tezel
 * @since 2022/07/30 21:16
 */
@Slf4j
@Service
public class RegisterServiceImpl implements IRegisterService {

    @Autowired
    MemberMapper memberMapper;

    @Autowired
    UserVerifyMapper verifyMapper;

    @Autowired
    JavaMailSender mailSender;

    /**
     * 用户注册
     * @author Tezel
     * @date 2022/07/30
     */
    @Override
    public UserRegisterResponse register(UserRegisterRequest registerRequest) {

        UserRegisterResponse response = new UserRegisterResponse();

        try {
            registerRequest.requestCheck();

            //验证用户名是否重复
            volidUserNameRepeat(registerRequest);

            //向用户表中插入一条数据
            Member member = new Member();
            member.setUsername(registerRequest.getUserName());
            member.setEmail(registerRequest.getEmail());
            //password加密
            String password = DigestUtils.md5DigestAsHex(registerRequest.getUserPwd().getBytes());
            member.setPassword(password);
            member.setCreated(new Date());
            member.setUpdated(new Date());
            member.setState(1);
            member.setIsVerified("N");


            int effectRows = memberMapper.insertSelective(member);

            if(effectRows != 1){
                response.setCode(UserRetCode.USER_REGISTER_FAILED.getCode());
                response.setMsg(UserRetCode.USER_REGISTER_FAILED.getMessage());
                return response;
            }

            //向用户验证表中插入一条记录
            UserVerify userVerify = new UserVerify();
            userVerify.setUsername(member.getUsername());
            String key = member.getUsername()+member.getPassword()+ UUID.randomUUID().toString();
            String uuid = DigestUtils.md5DigestAsHex(key.getBytes());
            userVerify.setUuid(uuid);
            userVerify.setRegisterDate(new Date());
            userVerify.setIsExpire("N");
            userVerify.setIsVerify("N");

            int rows = verifyMapper.insert(userVerify);
            if(rows != 1){
                response.setCode(UserRetCode.USER_REGISTER_VERIFY_FAILED.getCode());
                response.setMsg(UserRetCode.USER_REGISTER_VERIFY_FAILED.getMessage());
                return response;
            }


            //TODO 发送用户激活邮件
            sendEmail(uuid,registerRequest);


            response.setCode(UserRetCode.SUCCESS.getCode());
            response.setMsg(UserRetCode.SUCCESS.getMessage());

        }catch (Exception e){
            log.error("RegisterServiceImpl.register occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }

        return response;
    }

    /**
     * 用户注册激活
     * @author Tezel
     * @date 2022/07/31
     */
    @Override
    public UserVerifyResponse verify(UserVerifyRequest verifyRequest) {
        UserVerifyResponse response = new UserVerifyResponse();

        try{
            verifyRequest.requestCheck();

            UserVerify userVerify = new UserVerify();
            userVerify.setUuid(verifyRequest.getUuid());
            userVerify.setUsername(verifyRequest.getUserName());

            //用user_verify中查到的id,修改member中的验证状态
            //修改user_verify的信息
            updateUserVerify(userVerify);

            //如果没出现异常，可以通过username修改member标准的信息
            updateMember(verifyRequest.getUserName());


            response.setCode(UserRetCode.SUCCESS.getCode());
            response.setMsg(UserRetCode.SUCCESS.getMessage());

        }catch (Exception e){
            log.error("RegisterServiceImpl.verify occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }


        return response;
    }

    /**
     * 更新member表中的验证状态
     * @author Tezel
     * @date 2022/07/31
     */
    private void updateMember(String username) {
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username", username);

        List<Member> members = memberMapper.selectByExample(example);
        Member member = members.get(0);

        member.setIsVerified("Y");
        member.setUpdated(new Date());

        int i = memberMapper.updateByExample(member, example);

        if(i != 1 ){
            throw new ValidateException(UserRetCode.SYSTEM_ERROR.getCode(),
                    UserRetCode.SYSTEM_ERROR.getMessage());
        }

    }

    /**
     * 修改user_verify中的验证状态
     * @author Tezel
     * @date 2022/07/31
     */
    private void updateUserVerify(UserVerify userVerify) {
        Example example = new Example(UserVerify.class);
        example.createCriteria().andEqualTo("uuid",userVerify.getUuid())
        .andEqualTo("username", userVerify.getUsername());

        //用户注册验证表数据是否存在
        List<UserVerify> verifyList = verifyMapper.selectByExample(example);

        if(CollectionUtils.isEmpty(verifyList)){
            throw new ValidateException(UserRetCode.USERVERIFY_INFOR_INVALID.getCode(),
                    UserRetCode.USERVERIFY_INFOR_INVALID.getMessage());
        }

        UserVerify updateData = verifyList.get(0);

        //更新验证状态
        updateData.setIsVerify("Y");

        int i = verifyMapper.updateByPrimaryKeySelective(updateData);

        if(i != 1 ){
            throw new ValidateException(UserRetCode.SYSTEM_ERROR.getCode(),
                    UserRetCode.SYSTEM_ERROR.getMessage());
        }

    }

    /**
     * 发送用户激活邮件
     * @author Tezel
     * @date 2022/07/31
     */
    private void sendEmail(String uuid, UserRegisterRequest registerRequest) {

        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setSubject("CSmall用户激活");
        mailMessage.setFrom("tzmacip09@163.com");
        mailMessage.setTo(registerRequest.getEmail());
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("http://localhost:8101/user/verify?uid=").append(uuid).append("&username=").append(registerRequest.getUserName());
        mailMessage.setText(stringBuffer.toString());

        mailSender.send(mailMessage);

    }

    /**
     * 验证用户名是否重复
     * @author Tezel
     * @date 2022/07/30
     */

    private void volidUserNameRepeat(UserRegisterRequest registerRequest) {

        Example example = new Example(Member.class);

        example.createCriteria().andEqualTo("username", registerRequest.getUserName());

        List<Member> memberList = memberMapper.selectByExample(example);

        if (!CollectionUtils.isEmpty(memberList)) {
            //重复
            throw new ValidateException(UserRetCode.USERNAME_ALREADY_EXISTS.getCode(),
                    UserRetCode.USERNAME_ALREADY_EXISTS.getMessage());
        }

    }
}

